import request from '@/utils/request'
import { removeTokenInfo } from '@/utils/storage'
import { LOGOUT } from '../contants/login'
import { SAVE_PROFILE, SAVE_USER } from '../contants/profile'

/**
 * 获取用户信息
 * @returns
 */
export const getUser = () => {
  return async (dispatch) => {
    const { data: res } = await request.get('/user')
    dispatch(saveUser(res))
  }
}

/**
 * 存储用户信息
 * @param {object} payload
 * @returns
 */
export const saveUser = (payload) => ({ type: SAVE_USER, payload })

/**
 * 获取个人资料
 * @returns
 */
export const getUserProfile = () => {
  return async (dispatch) => {
    const res = await request.get('/user/profile')
    // console.log(res)
    dispatch(saveUserProfile(res.data))
  }
}

// 存储个人资料
export const saveUserProfile = (payload) => ({ type: SAVE_PROFILE, payload })

// 修改用户信息
export const EditProfile = (data) => {
  return async (dispatch) => {
    await request.patch('/user/profile', data)
    dispatch(getUserProfile())
  }
}

// 更改头像
export const avatorChange = (photo) => {
  return async (dispatch) => {
    const res = await request.patch('/user/photo', photo)
    console.log(res)
    dispatch(getUserProfile())
  }
}

// 退出
export const logout = () => {
  return (dispatch) => {
    removeTokenInfo()
    dispatch({
      type: LOGOUT,
    })
  }
}
